﻿import numpy as np
import matplotlib.pyplot as plt

# 定义 ReLU 函数
def relu(x):
    return np.maximum(0, x)

# 定义 ReLU 的线性组合逼近函数
def approximate_quadratic(x):
    # 选择一些分段点和对应的斜率
    a1, b1 = 1, 0
    a2, b2 = 1, 1
    a3, b3 = -2, 2
    
    return (
        a1 * relu(x - b1) +
        a2 * relu(x - b2) +
        a3 * relu(x - b3)
    )

# 生成数据
x = np.linspace(-1, 3, 400)
y_true = x**2
y_approx = approximate_quadratic(x)

# 绘制图形
plt.plot(x, y_true, label='y = x^2', color='blue')
plt.plot(x, y_approx, label='ReLU Approximation', color='red', linestyle='--')
plt.title('ReLU Approximation of y = x^2')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()